package com.tqyan.service.chat.impl.novel;

import com.alibaba.fastjson.JSONObject;
import com.tqyan.dal.mapper.NovelMapper;
import com.tqyan.dal.mapper.NovelSceneMapper;
import com.tqyan.model.dto.*;
import com.tqyan.model.dto.paper.OutlineDTO;
import com.tqyan.model.dto.paper.PaperTitleDTO;
import com.tqyan.model.exp.DefaultException;
import com.tqyan.service.chat.AbstractChatPointService;
import com.tqyan.service.chat.ChatPointContent;
import com.tqyan.service.transfer.FileService;
import com.tqyan.util.GuidUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;

/**
 * @description 小说
 * <p> <功能详细描述> </p>
 *
 * @author 陈晨
 * @date 2023/6/13 17:30
 */
@Service
@Slf4j
public class NovelChatPointService extends AbstractChatPointService {

    @Autowired
    private NovelMapper novelMapper;
    @Autowired
    private NovelSceneMapper novelSceneMapper;
    @Autowired
    private NovelViewChatPointService novelViewChatPointService;
    @Autowired
    private FileService fileService;

    @Override
    public String getPoint() {
        return ChatPointContent.NOVEL;
    }

    @Override
    public ChatContentDTO chatPoint(UserDTO user, UserSettingDTO userSetting, ChatDTO chat, String content) {
        // 1, 获取小说标题
        content = content.replaceAll("：", ":");
        String title = null;
        if (content.split(":").length >= 2) {
            title = content.split(":")[1].trim();
        }
        // 2.1, 无标题: 转小说查询
        if (StringUtils.isBlank(title)) {
            return novelViewChatPointService.chat(user, userSetting, chat, ChatPointContent.NOVEL_VIEW);
        }
        // 3.1, 有标题: 查询标题是否存在
        NovelDTO novel = novelMapper.queryByTitle(user.getId(), title);
        // 3.2, 有标题: 标题存在, 转小说查询
        if (null != novel) {
            String viewContent = ChatPointContent.NOVEL_VIEW + ":" + title;
            return novelViewChatPointService.chat(user, userSetting, chat, viewContent);
        }
        // 3.3, 有标题: 标题不存在, 新建小说, 选择小说类型
        String questionContent = String.format(ChatPointContent.ANSWER_1006
                , title, title
                , title, title
                , title, title
                , title, title
                , title, title
                , title, title
                , title, title
                , title, title
                , title);
        // 记录对话
        ChatContentDTO question = super.createQuestion(user, userSetting, chat, content, null, null);
        return super.createAnswer(userSetting, question, questionContent);
    }

    /**
     * @description 上传word
     * <p> <功能详细描述> </p>
     *
     * @author 陈晨
     * @date 2023/5/17 21:00
     */
    public String uploadWord(NovelDTO novel) {
        if (null == novel) {
            return null;
        }
        List<NovelSceneDTO> novelSceneList = novelSceneMapper.queryByNovel(novel.getUserId(), novel.getId());

        // 创建文档对象
        XWPFDocument document = new XWPFDocument();

        // 中文标题
        XWPFParagraph paragraph = document.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun run = paragraph.createRun();
        run.setText(novel.getTitle());
        run.setFontFamily("微软雅黑");
        run.setFontSize(18);
        document.createParagraph();
        // 类型
        paragraph = document.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.CENTER);
        run = paragraph.createRun();
        run.setText(novel.getType());
        run.setFontFamily("微软雅黑");
        run.setFontSize(10);
        document.createParagraph();

        // 正文
        for (NovelSceneDTO novelScene : novelSceneList) {
            if (null == novelScene || StringUtils.isBlank(novelScene.getContent())) {
                continue;
            }
            paragraph = document.createParagraph();
            paragraph.setAlignment(ParagraphAlignment.LEFT);
            paragraph.setIndentationFirstLine(8);
            run = paragraph.createRun();
            run.setText(novelScene.getContent());
            run.setFontFamily("宋体");
            run.setFontSize(10);
            document.createParagraph();
        }

        // 生成文档
        String fileName = novel.getFileName();
        if (StringUtils.isBlank(fileName)) {
            fileName = novel.getTitle() + "_" + GuidUtil.getUUID() + ".docx";
            // 更新文件名
            NovelDTO updateNovel = new NovelDTO();
            updateNovel.setId(novel.getId());
            updateNovel.setUserId(novel.getUserId());
            updateNovel.setFileName(fileName);
            novelMapper.update(updateNovel);
        }
        File file = new File(FileService.FOLDER_LOCAL_TEMP + fileName);
        // 上传OSS
        try {
            // 小程序码
            paragraph = document.createParagraph();
            paragraph.setAlignment(ParagraphAlignment.CENTER);
            run = paragraph.createRun();
            FileInputStream imageStream = new FileInputStream(FileService.MINI);
            run.addPicture(imageStream, Document.PICTURE_TYPE_PNG, FileService.MINI.getName()
                    , Units.toEMU(150), Units.toEMU(150));
            imageStream.close();
            run = paragraph.createRun();
            run.setText("\t\t");
            run.setFontFamily("黑体");
            run.setFontSize(16);

            // 管理员微信
            run = paragraph.createRun();
            imageStream = new FileInputStream(FileService.MANAGER);
            run.addPicture(imageStream, Document.PICTURE_TYPE_PNG, FileService.MANAGER.getName()
                    , Units.toEMU(150), Units.toEMU(150));
            imageStream.close();

            // 输出文档
            FileOutputStream out = new FileOutputStream(file);
            document.write(out);
            out.close();
            // 上传OSS
            fileService.uploadAliyunOSS(file, FileService.FOLDER_NOVEL, fileName);
            return fileName;
        } catch (Exception e) {
            log.error("[{}] 文件上传OSS失败, {}", this.getPoint(), e.getMessage(), e);
            throw new DefaultException(e.getMessage());
        } finally {
            file.delete();
        }
    }

}


